import com.shopping.cart.auth.Authority
import com.shopping.cart.auth.Person
import java.lang.management.ManagementFactory
import javax.management.MBeanServer
import javax.management.ObjectName
import net.sf.ehcache.management.ManagementService
import org.hibernate.jmx.StatisticsService
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.context.support.WebApplicationContextUtils

class BootStrap {

    def sessionFactory
    def cacheManager
    def init = {servletContext ->

        if(!Authority.findByAuthority('ROLE_USER')) {
            new Authority(description: 'Basic user role', authority: 'ROLE_USER').save()
        }

        if(!Authority.findByAuthority('ROLE_ADMIN')) {
            new Authority(description: 'Admin user role', authority: 'ROLE_ADMIN').save()
        }

        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext)
        def authenticateService = wac.getBean('authenticateService')

        if(!Person.findByUsername('admin')) {
            Person person = new Person(username:'admin',userRealName:'Admin User', enabled:true,
                    email:'glenn.saqui@gmail.com', emailShow:false, passwd: authenticateService.encodePassword('r8oogcpr'))
            person.addToAuthorities(Authority.findByAuthority('ROLE_ADMIN'))
            assert person.save(flush:true)
        }

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer()

        // Define ObjectName of the MBean
        ObjectName on = new ObjectName("Hibernate:type=statistics,application=Shwitter");

        // Enable Hibernate JMX Statistics
        StatisticsService statsMBean = new StatisticsService();
        statsMBean.setSessionFactory(sessionFactory);
        statsMBean.setStatisticsEnabled(true);
        mbs.registerMBean(statsMBean, on);

        /**
         * Enable Ehcache JMX Statistics
         * Use CacheManager.getInstance() instead of new CacheManager()
         * as net.sf.ehcache.hibernate.SingletonEhCacheProvider is used
         * to ensure reference to the same CacheManager instance as used
         * by Hibernate
         */
        ManagementService.registerMBeans(cacheManager, mbs, true, true, true, true);
    }

    def destroy = {
    }
}